package main

import (
	"bytes"
	"context"
	"crypto/ecdsa"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"log"
	"math/big"
	"net/http"
	"strings"

	"Contract"

	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/ethclient"
)

func main() {
	Deploy()
	//commitTx()
	//test3()
}

const key = `
{"address":"f9a0c4edb6d58562264eea1d8a89eae81fb2e0d2","crypto":{"cipher":"aes-128-ctr","ciphertext":"684226d846600058a775b814630d5121c287df7dc151dbe614874fec4445366c","cipherparams":{"iv":"097b7c802de769c970dba335e83e4c40"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"ddaa0aaba451b18b7743918bd26eb403b7ec22841546b2ff6fd0dbf832481c5b"},"mac":"59c65f69d92cae3faa8c087965ae237267544d2c5018c0b6538ed7cbe7740209"},"id":"bafbe1ac-3ced-4a58-941b-d2db3ced7e9a","version":3}
`

func testPost() {
	url := "http://119.29.136.113:8888/score/receiveData" //你要请求的url地址
	cx_json := "{\"cjhx\":\"aaa\"}"                       //传递的json格式的参数，有时需要格式化
	var jsonStr = []byte(cx_json)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))

	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)

	if err != nil {
		panic(err)
	}

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println("response Body:", string(body))
}

func Deploy() {
	client, err := ethclient.Dial("http://175.178.47.107:8501")
	if err != nil {
		log.Fatal(err)
	}

	privateKey, err := crypto.HexToECDSA("f1ca9a37066b3e50cdd836366834912ba4ceec48c7f0bced4da9fbb65207f693")
	if err != nil {
		log.Fatal(err)
	}

	publicKey := privateKey.Public()
	publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
	if !ok {
		log.Fatal("cannot assert type: publicKey is not of type *ecdsa.PublicKey")
	}

	fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)
	nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
	if err != nil {
		log.Fatal(err)
	}

	gasPrice, err := client.SuggestGasPrice(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	auth := bind.NewKeyedTransactor(privateKey)
	auth.Nonce = big.NewInt(int64(nonce))
	auth.Value = big.NewInt(0)     // in wei
	auth.GasLimit = uint64(300000) // in units
	auth.GasPrice = gasPrice

	address, tx, instance, err := Contract.DeployEvidence(auth, client)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(address.Hex())   // 0x147B8eb97fD247D06C4006D269c90C1908Fb5D54
	fmt.Println(tx.Hash().Hex()) // 0xdae8ba5444eefdc99f4d45cd0c4f24056cba6a02cefbf78066ef9f4188ff7dc0

	_ = instance
}

//0x9eF157D9dCe5E5bC5711fb338972f4d603B378cd

func test() {
	client, err := ethclient.Dial("https://kovan.infura.io/v3/e6b151ba42004b5ebce395b52fa4de91")
	if err != nil {
		log.Fatal(err)
	}

	privateKey, err := crypto.HexToECDSA("f1ca9a37066b3e50cdd836366834912ba4ceec48c7f0bced4da9fbb65207f693")
	if err != nil {
		log.Fatal(err)
	}

	publicKey := privateKey.Public()
	publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
	if !ok {
		log.Fatal("cannot assert type: publicKey is not of type *ecdsa.PublicKey")
	}

	fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)
	nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
	if err != nil {
		log.Fatal(err)
	}

	gasPrice, err := client.SuggestGasPrice(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	auth, err := bind.NewTransactorWithChainID(strings.NewReader(key), "123", big.NewInt(42))
	if err != nil {
		log.Fatal(err)
	}
	auth.Nonce = big.NewInt(int64(nonce))
	auth.Value = big.NewInt(0)      // in wei
	auth.GasLimit = uint64(3000000) // in units
	auth.GasPrice = gasPrice

	address, tx, instance, err := Contract.DeployEvidence(auth, client)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(address.Hex())   // 0x147B8eb97fD247D06C4006D269c90C1908Fb5D54
	fmt.Println(tx.Hash().Hex()) // 0xdae8ba5444eefdc99f4d45cd0c4f24056cba6a02cefbf78066ef9f4188ff7dc0

	_ = instance
}

func commitTx() {
	//http://175.178.47.107:8501
	client, err := ethclient.Dial("https://kovan.infura.io/v3/e6b151ba42004b5ebce395b52fa4de91")
	if err != nil {
		log.Fatal(err)
	}

	privateKey, err := crypto.HexToECDSA("f1ca9a37066b3e50cdd836366834912ba4ceec48c7f0bced4da9fbb65207f693")
	if err != nil {
		log.Fatal(err)
	}

	publicKey := privateKey.Public()
	publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
	if !ok {
		log.Fatal("cannot assert type: publicKey is not of type *ecdsa.PublicKey")
	}

	fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)
	nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
	if err != nil {
		log.Fatal(err)
	}

	//value := big.NewInt(2000000000000000) // in wei (1 eth)
	//gasLimit := uint64(21000)             // in units
	gasPrice, err := client.SuggestGasPrice(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	auth, err := bind.NewTransactorWithChainID(strings.NewReader(key), "123", big.NewInt(42))
	auth.Nonce = big.NewInt(int64(nonce))
	auth.Value = big.NewInt(0)      // in wei
	auth.GasLimit = uint64(3000000) // in units
	auth.GasPrice = gasPrice
	address := common.HexToAddress("0x5eE4E7cD0d09B26d2A5C01c345d9Ca969C59a88b")
	//0xBc7EFF643feA9737E12A9E33e35F630b0CD8Ee58
	//0x5eE4E7cD0d09B26d2A5C01c345d9Ca969C59a88b
	instance, err := Contract.NewEvidence(address, client)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("contract is loaded")
	//hashscort := []byte("723b4aba03187c9f6cascascas916f5f1a0f206d48ba09d46e81fdf484d9")
	str := "15d6sa15d6asvdsavdsvds159"
	hash := sha256.New()
	hash.Write([]byte(str))
	hex_byte_data := hash.Sum(nil)

	//copy(hashscort[:], []byte("723b4aba03187c9f627ac67a8282f7916f5f1a0f206d48ba09d46e81fdf484d9"))
	//fmt.Println(hashscort)
	//0x082b4aba03187c9f627ac67a8282f7916f5f1a0f206d48ba09d46e81fdf484d4
	//tx, err := instance.SaveEvidence(auth, hashscort)
	tx, err := instance.SaveEvidence(auth, hex_byte_data)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("tx sent: %s\n", tx.Hash().Hex()) // tx sent: 0x8d490e535678e9a24360e955d75b27ad307bdfb97a1dca51d0f3035dcee3e870

	//fmt.Println(address.Hex())   // 0x6045A09071E0c6043b0938015Ee0159dD4aa4357 contract
	//fmt.Println(tx.Hash().Hex()) // 0x5204614d9dce723803034da4ee92847ef06af620367ba62c5fbe7029fdbe1323 trastion hash

	_ = instance
}

func test3() {
	//https://kovan.infura.io/v3/e6b151ba42004b5ebce395b52fa4de91
	//http://175.178.47.107:8501
	client, err := ethclient.Dial("http://175.178.47.107:8501")
	if err != nil {
		log.Fatal(err)
	}
	txHash := common.HexToHash("0x6082a9b7e4e8af5f6d440ae6cb26c7dc77a2d4e4d8020f8b24fea540a3925dc0")
	tx, _, err := client.TransactionByHash(context.Background(), txHash)
	if err != nil {
		log.Fatal(err)
	}

	//fmt.Println(tx.Hash().Hex()) // 0x5d49fcaa394c97ec8a9c3e7bd9e8388d420fb050a52083ca52ff24b3b65bc9c2
	//receipt, err := client.TransactionReceipt(context.Background(), tx.Hash())
	if err != nil {
		log.Fatal(err)
	}
	//fmt.Println(receipt.Logs[0])
	s := tx.Data()
	b := s[68:]
	fmt.Printf("%+v\n", tx.Data())
	fmt.Println(hex.EncodeToString(b))
	//hex_string_data := hex.EncodeToString(receipt.Logs[0].Data[96:])
	//fmt.Println(hex_string_data)
	//fmt.Println(string(hex_string_data))

}
